package com.crr.dao.impl;

import com.crr.dao.UserDao;
import com.crr.entity.User;
import com.crr.utils.DBUtils;

import java.sql.*;

public class UserDaoImpl implements UserDao {
    Connection conn = DBUtils.getConn();
    PreparedStatement ps = null;
    ResultSet rs = null;

    int n = 0;

    @Override
    public int userReg(String un, String psw) {

        try {
            String sql = "insert into user(u_name,u_psw)values (?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1, un);
            ps.setString(2, psw);
            n = ps.executeUpdate();
            return n;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtils.closeTwo(ps, conn);
        }

    }

    @Override
    public User userLogin(String username, String psw) {
        User u = null;
        try {
            String sql = "select * from user where u_name = ? and u_psw = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, psw);
            rs = ps.executeQuery();
            if (rs.next()) {
                int uid = rs.getInt("u_id");
                String un = rs.getString("u_name");
                String upsw = rs.getString("u_psw");
                u = new User(uid, un, upsw);

            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtils.closeAll(rs, ps, conn);
        }

        return u;
    }

    @Override
    public boolean checkUserName(String username) {
        boolean flag = false;
        String sql = "select u_name from user where u_name = ? ";
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            rs = ps.executeQuery();
            if (rs.next()) {
                flag = true;
            }
            return flag;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtils.closeAll(rs, ps, conn);
        }

    }
}
